/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.henryschein.mmvvcc.parser;

import com.henryschein.mmvvcc.model.Person;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author obelog
 */
public class PaserXML {
    
    private static Logger log = Logger.getLogger(PaserXML.class.getName());

    private String readFile(String file) {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        try {
            String sCurrentLine = null;
            br = new BufferedReader(new FileReader(file));
            while ((sCurrentLine = br.readLine()) != null) {
                sb.append(sCurrentLine);
            }
        } catch (IOException e) {
            log.info(e.toString());
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException ex) {
                log.info(ex.toString());
            }
        }
        return sb.toString();
    }
    
    public List<Person> parse(String file){
        List<Person> list = new ArrayList<Person>();
        String s = readFile(file);
        Pattern p = Pattern.compile("<quote>.*?</quote>");
        Pattern p1 = Pattern.compile("<cont>.*?</cont>");
        Pattern p2 = Pattern.compile("<cat>.*?</cat>");
        Pattern p3 = Pattern.compile("<vote>.*?</vote>");
        Matcher m = p.matcher(s);
        while (m.find()) {
            String res = m.group();
            res = res.replace("<quote>", "");
            res = res.replace("</quote>", "");
            Matcher m1 = p1.matcher(res);
            m1.find();
            
            Person pers = new Person();
            
            String unit = m1.group();
            unit = unit.replace("<cont>", "");
            unit = unit.replace("</cont>", "");
            pers.setQuote(unit);
            
            Matcher m2 = p2.matcher(res);
            m2.find();
            unit = m2.group();
            unit = unit.replace("<cat>", "");
            unit = unit.replace("</cat>", "");
            pers.setCategory(unit);
            
            Matcher m3 = p3.matcher(res);
            m3.find();
            unit = m3.group();
            unit = unit.replace("<vote>", "");
            unit = unit.replace("</vote>", "");
            pers.setVote(unit);
            
            list.add(pers);
        }
        return list;
    }
    
}
